﻿using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using ClientDependency.Core;
using ClientDependency.Core.Config;
using ClientDependency.Core.FileRegistration.Providers;

namespace Creative.Website.Starter.ClientDependency
{
    public class Html5StandardRenderer : BaseRenderer
    {
        public const string DefaultName = "Html5StandardRenderer";

        public override void Initialize(string name, NameValueCollection config)
        {
            if (string.IsNullOrEmpty(name))
            {
                name = DefaultName;
            }
              
            base.Initialize(name, config);
        }

        protected override string RenderJsDependencies(List<IClientDependencyFile> jsDependencies)
        {
            if (jsDependencies.Count == 0)
            {
                return string.Empty;
            }

            var stringBuilder = new StringBuilder();
            if (ConfigurationHelper.IsCompilationDebug || !EnableCompositeFiles)
            {
                foreach (var clientDependencyFile in jsDependencies)
                {
                    stringBuilder.AppendLine(RenderSingleJsFile(clientDependencyFile.FilePath));
                }
            }
            else
            {
                foreach (var js in ProcessCompositeList(jsDependencies, ClientDependencyType.Javascript))
                {
                    stringBuilder.AppendLine(RenderSingleJsFile(js));
                }
            }

            return stringBuilder.ToString();
        }

        protected override string RenderCssDependencies(List<IClientDependencyFile> cssDependencies)
        {
            if (cssDependencies.Count == 0)
            {
                return string.Empty;
            }

            var stringBuilder = new StringBuilder();
            if (ConfigurationHelper.IsCompilationDebug || !EnableCompositeFiles)
            {
                foreach (var clientDependencyFile in cssDependencies)
                {
                    stringBuilder.AppendLine(RenderSingleCssFile(clientDependencyFile.FilePath));
                }
            }
            else
            {
                foreach (var css in ProcessCompositeList(cssDependencies, ClientDependencyType.Css))
                {
                    stringBuilder.AppendLine(RenderSingleCssFile(css));
                }
            }

            return stringBuilder.ToString();
        }

        protected override string RenderSingleJsFile(string js)
        {
            return string.Format("<script src=\"{0}\"></script>", HttpUtility.HtmlEncode(js));
        }

        protected override string RenderSingleCssFile(string css)
        {
            return string.Format("<link rel=\"stylesheet\" href=\"{0}\" />", HttpUtility.HtmlEncode(css));
        }
    }
}
